import time
import logging
import threading

from tornado.ioloop import IOLoop
from tornado.web import Application
from tornado_http2.server import Server

from QUANTAXIS_WEBSERVER.QAWebServer.QA_Web import main as web_start
from QATrader.QATRADER.webhandler import webserver, TradeAccountHandler, SendOrderHandler
from QATrader.QATRADER.ws_server import WebSocketServer
from QUANTAXIS_RealtimeCollector.QARealtimeCollector.collectors.stock_min_bar_collector import QARTCStockMinBar
from QUANTAXIS_RealtimeCollector.QARealtimeCollector.collectors.stock_day_bar_collector import QARTCStockDayBar
from QUANTAXIS_RealtimeCollector.QARealtimeCollector.datahandler.stock_resampler import QARTCStockBarResampler

def main():
    # web start
    threading.Thread(target=web_start, daemon=True).start()
    logging.info('web start')

    # start websocket server
    server = WebSocketServer()
    threading.Thread(target=server.begin, daemon=True).start()
    logging.info('web socket start')

    # rtc
    delay = 30  # 更新间隔
    # 分钟线
    minbar = QARTCStockMinBar(delay=delay, debug=False, frequency='1min')
    minbar.start()
    # 日线
    daybar = QARTCStockDayBar(delay=delay, debug=False, frequency='1day')
    daybar.start()
    print('Start realtime collector')

    # resample
    freqs = ['1min', '5min', '15min', '60min']
    for f in freqs:
        QARTCStockBarResampler(frequency=f).start()
        print('Resample codes to %s' % f)
        time.sleep(1)

    # start web server
    # threading.Thread(target=webserver, daemon=True).start()
    # webserver()
    handlers = [(r'/tradeaccounts', TradeAccountHandler),
                (r'/order', SendOrderHandler)]

    apps = Application(
        handlers=handlers,
        debug=True,
        autoreload=True,
        compress_response=True
    )
    http_server = Server(apps)
    http_server.bind('8020', address='0.0.0.0')
    http_server.start(1)
    IOLoop.current().start()
    logging.info('web server start')




if __name__ == "__main__":
    try:
        from QUANTAXIS_RealtimeCollector.QARealtimeCollector.utils.logconf import update_log_file_config
        logfile = 'stock.sim.log'
        logging.config.dictConfig(update_log_file_config(logfile))
    except Exception as e:
        print(e.__str__())
    main()